package com.pyf.ui.util;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.ListContainer;
import ohos.agp.components.ScrollView;

/**
 * @author 裴云飞
 * @date 2020/12/27
 */

public class ScrollUtil {

    /**
     * 判断child是否发生了滚动
     *
     * @param child
     * @return true 发生了滚动
     */
    public static boolean childScrolled(Component child) {
        if (child instanceof ScrollView) {
            ScrollView scrollView = (ScrollView) child;
            if (scrollView.getComponentAt(0) != null
                    && scrollView.getComponentAt(0).getTop() < 0) {
                return true;
            }
        } else if (child.getScrollValue(Component.AXIS_Y) > 0) {
            return true;
        }
        if (child instanceof ListContainer) {
            ListContainer listContainer = (ListContainer) child;
            Component component = listContainer.getComponentAt(0);
            int firstPosition = listContainer.getIndexForComponent(component);
            return firstPosition != 0 || component.getTop() != 0;
        }
        return false;
    }

    /**
     * 查找可以滚动的child
     *
     * @return 可以滚动的child
     */
    public static Component findScrollableChild(ComponentContainer componentContainer) {
        Component child = componentContainer.getComponentAt(1);
        if (child instanceof ScrollView || child instanceof ListContainer) {
            return child;
        }
        if (child instanceof ComponentContainer) {//往下多找一层
            Component tempChild = ((ComponentContainer) child).getComponentAt(0);
            if (tempChild instanceof ScrollView || tempChild instanceof ListContainer) {
                child = tempChild;
            }
        }
        return child;
    }
}
